package com.example.questionsystem.modules.qu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.questionsystem.core.api.ApiRest;
import com.example.questionsystem.core.api.controller.BaseController;
import com.example.questionsystem.modules.qu.Vo.ProjectSubjects;
import com.example.questionsystem.modules.qu.entity.Projects;
import com.example.questionsystem.modules.qu.entity.SubjectSessions;
import com.example.questionsystem.modules.qu.service.ProjectsService;
import com.example.questionsystem.modules.qu.service.SubjectsService;
import com.example.questionsystem.modules.qu.service.util.ChineseNumberConverter;
import com.example.questionsystem.modules.qu.util.AESDecryptor;
import com.example.questionsystem.modules.qu.util.DateFormatUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.example.questionsystem.modules.qu.util.NestedJsonParserUtil.getValuesByPaths;

@Slf4j
@Api(tags = {"考前模板"})
@RestController
@RequestMapping("/template")
public class templateController extends BaseController {

    @Resource
    private ProjectsService projectsService;
    @Resource
    private SubjectsService subjectsService;


    @ResponseBody
    @GetMapping("/list")
    public ApiRest list() {
        List<ProjectSubjects> projectsSubjects = new ArrayList<>();
        List<Projects> projects = projectsService.list();
        for (Projects project : projects){
            List<SubjectSessions> subjectSessionsByProjectId = subjectsService.getSubjectSessionsByProjectId(project.getProjectId());
            ProjectSubjects projectSubject = new ProjectSubjects(project, subjectSessionsByProjectId);
            projectsSubjects.add(projectSubject);
        }
        return success(projectsSubjects);
    }

    @ResponseBody
    @PostMapping("/save")
    public ApiRest save(@RequestBody ProjectSubjects projectSubjects) {
        Projects projects = projectSubjects.getProjects();
        List<SubjectSessions> subjects = projectSubjects.getSubjects();
        if(projects == null || subjects == null){
            return failure("参数错误");
        }
        projectsService.saveProjects(projects);

        subjectsService.saveSubjectSessions(subjects);
        return success();
    }

    @ResponseBody
    @PostMapping("/upload")
    public ApiRest uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        // 读取文件内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
        String key = "JD333!@#"; // 6字节key
        String iv = "JD333!@#";  // 6字节iv
        String content = AESDecryptor.decryptFile(file, key, iv);

        JSONObject jsonObject = JSONObject.parseObject(content);
        Projects projects = new Projects();
        ArrayList<SubjectSessions> subjectSessionsList = new ArrayList<>();
        if (jsonObject == null){
            return  failure("解析失败");
        }
        List<String> paths = new ArrayList<>();
            paths.add("kszb.ksmc");
            paths.add("listKckm");
            paths.add("listKccckmfl");
            paths.add("listKccckm");
            paths.add("listKckm.kmxh");
            paths.add("kc.ksxmm");
            paths.add("kc.ksny");
            java.util.Map<String, Object> values = getValuesByPaths(jsonObject, paths);
            projects.setProjectId(   (String) values.get("kc.ksxmm") + "_" + (String) values.get("kc.ksny"));
            projects.setProjectName((String) values.get("kszb.ksmc"));
            projects.setSubjectCount(((JSONArray) values.get("listKckm")).size());
            projects.setCreatedAt(DateFormatUtils.formatDate(new Date()));
            projects.setUpdatedAt(DateFormatUtils.formatDate(new Date()));
            if (values.get("listKccckm") != null){
                for (int i = 0; i < ((JSONArray) values.get("listKccckm")).size(); i++) {
                    SubjectSessions subjectSessions = new SubjectSessions();
                    subjectSessions.setProjectId(projects.getProjectId());
                    String s = ((String) ((JSONArray) values.get("listKccckm")).getJSONObject(i).get("kmxh"));
                    String SessionsNumber = ChineseNumberConverter.extractAndConvertChineseNumber((String) ((JSONArray) values.get("listKccckm")).getJSONObject(i).get("ccmc"));
                    subjectSessions.setSubjectId(projects.getProjectId()  + "_" + (String) ((JSONArray) values.get("listKccckm")).getJSONObject(i).get("kmxh") + "_" +  SessionsNumber );
                    subjectSessions.setSubjectName((String) ((JSONArray) values.get("listKccckm")).getJSONObject(i).get("kmmc"));
                    subjectSessions.setSessionName((String) ((JSONArray) values.get("listKccckm")).getJSONObject(i).get("ccmc"));
                    Date StartTime = ((JSONArray) values.get("listKccckm")).getJSONObject(i).getDate("kskssj");
                    subjectSessions.setKmxh((String) ((JSONArray) values.get("listKccckm")).getJSONObject(i).get("kmxh"));
                    subjectSessions.setStartTime(  DateFormatUtils.formatDate(StartTime));
                    Date endDate = ((JSONArray) values.get("listKccckm")).getJSONObject(i).getDate("ksjssj");
                    String endDates = DateFormatUtils.formatDate(endDate);
                    subjectSessions.setEndTime(endDates);
                    subjectSessionsList.add(subjectSessions);
                    //String creatDate = DateFormatUtils.formatDate(new Date());

                }
            }
        ProjectSubjects projectSubjects = new ProjectSubjects();
        projectSubjects.setProjects(projects);
        projectSubjects.setSubjects(subjectSessionsList);
        return success("解析成功",projectSubjects);
    }
}